//
//  SYJStatusOriginalView.swift
//  weibo
//
//  Created by 孙英建 on 16/4/20.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SnapKit

class SYJStatusOriginalView: UIView {

    // 记录原创微博的约束
     var originalViewBottomConstraint: Constraint?
    
    var statusModel: SYJStatusesModel?{
        didSet{
            
            // 为控件赋值
            iconImageView.sd_setImageWithURL(NSURL(string: statusModel?.user?.profile_image_url ?? ""), placeholderImage: UIImage(named: "avatar_default_big"))
            
            nameLabel.text = statusModel?.user?.screen_name
            
            mbrankImageView.image = getmbrankImage(statusModel?.user?.mbrank ?? 0)
            
            timeLabel.text = getWeiboTimeString(statusModel!.created_at!)
            
            sourceLabel.attributedText = getSourceString(statusModel?.source)
            
            verifiedImageView.image = getverifiedImage((statusModel?.user?.verified_type) ?? -1)
            
            contentLabel.text = statusModel?.text
            
            // 卸载自身的约束
            self.originalViewBottomConstraint?.uninstall()
            
            // 判断有无配图
            if statusModel?.pic_urls?.count != 0{
                pictureView.pictureInfo = statusModel?.pic_urls
                
                self.snp_makeConstraints(closure: { (make) -> Void in
                    self.originalViewBottomConstraint = make.bottom.equalTo(pictureView.snp_bottom).offset(10).constraint
                })
                // 显示配图
                pictureView.hidden = false
            }else{
                self.snp_makeConstraints(closure: { (make) -> Void in
                    self.originalViewBottomConstraint = make.bottom.equalTo(contentLabel.snp_bottom).offset(10).constraint
                })
                // 隐藏我们的配图
                pictureView.hidden = true
            }
            
            
        }
    }
    
    
    // 处理来源文字
    func getSourceString(source: String?) -> NSMutableAttributedString{
        
        guard let s = source where s.containsString("\">") else{
            return NSMutableAttributedString(string: "")
        }
        
        let startRange = s.rangeOfString("\">")!
        let endRange = s.rangeOfString("</a")!
        
        
        let result = s.substringWithRange(startRange.endIndex..<endRange.startIndex)
        // 拼接后最终显示的结果
        let name = "来自 \(result)"
        // 通过富文本
        let attr = NSMutableAttributedString(string: name)
        
        // 转name 为NSString 然后获取nsrange
        let range = (name as NSString).rangeOfString("来自")
        // 通过富文本更改指定位置的属性
        attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.grayColor(), range: range)
        
        //  设置富文本指定位置的字体大小
        //attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(18), range: range)
        
        return attr
    }
    
    /*
    - 微博时间字符串处理
    - 业务需求逻辑
    - 如果是今年
    - 如果是今天
    - 如果 < 60 s  显示格式: 刚刚
    - 如果 >=60 && < 60 * 60  显示格式: xx分钟前
    - 其他 显示格式: xx小时前
    - 如果是昨天
    -例如 2016-04-22 19:19:19  显示格式: 昨天 19:19
    - 其他
    -例如 2016-04-04 20:20:20  显示格式: 04月04日 20:20
    - 如果不是今年
    -例如: 2015-01-01 18:18:18 显示格式: 2015年01月01日 18:18
    */
    // 处理微博时间
    func getWeiboTimeString(weiboTime: String) -> String{
        
        let df = NSDateFormatter()
        // 设置格式
        // Fri Apr 22 17:15:54 +0800 2016
        df.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        df.locale = NSLocale(localeIdentifier: "en_US")
        
        let weiboDate = df.dateFromString(weiboTime)!
        
        let isThisYear: Bool = weiboTimeIsThisYear(weiboDate)

        if isThisYear{
            // 今年
            let calendar =  NSCalendar.currentCalendar()
            
            if calendar.isDateInToday(weiboDate){
                // 今天
                let s = NSDate().timeIntervalSinceDate(weiboDate)
                
                if s < 60 {
                    return "刚刚"
                }else if s >=  60 && s < 60 * 60 {
                    return "\(Int(s / 60))分钟前"
                }else {
                    return "\(Int(s / 60 / 60))小时前"
                }
                
            }else if calendar.isDateInYesterday(weiboDate) {
                // 昨天
                df.dateFormat = "昨天 HH:mm"
                return df.stringFromDate(weiboDate)
            }else{
                // 其它 
                df.dateFormat = "MM月dd日 HH:mm"
                return df.stringFromDate(weiboDate)
            }

        }else{
            // 不是今年
            df.dateFormat = "yyyy年MM月dd日 HH:mm"
            return df.stringFromDate(weiboDate)
        }
    }
    
    // 判断是否是今年
    func weiboTimeIsThisYear(weiboDate: NSDate) -> Bool{
        let df = NSDateFormatter()
        df.dateFormat = "yyyy"
        df.locale = NSLocale(localeIdentifier: "en_US")
        
        // 当前时间字符串
        let currentStr = df.stringFromDate(NSDate())
        // 微博时间字符串
        let weiboStr = df.stringFromDate(weiboDate)
        
        if currentStr == weiboStr {
            return true
        }else{
            return false
        }
        
    }
    
    
    // 会员等级 0-6 判断
    func getmbrankImage(mbrank: Int) -> UIImage?{
        if mbrank > 0 && mbrank < 7{
            return UIImage(named: "common_icon_membership_level\(mbrank)")
        }else{
            return UIImage(named:"common_icon_membership_expired")
        }
    }
    
    // 认证类型，-1：没有认证，0，认证用户，2,3,5: 企业认证，220: 达人
    func getverifiedImage(verified: Int) -> UIImage? {
        switch verified{
        case 0:
            return UIImage(named: "avatar_vip")
        case 2,3,5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        default:
            return nil
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 添加控件
        setUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    // 设置控件
    func setUI(){
        
        self.backgroundColor = UIColor.whiteColor()
      
        addSubview(iconImageView)
        addSubview(nameLabel)
        addSubview(mbrankImageView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(verifiedImageView)
        addSubview(contentLabel)
        addSubview(pictureView)
        
        // 添加约束
        
        // 头
        iconImageView.snp_makeConstraints { (make) -> Void in
            make.top.leading.equalTo(10)
            make.size.equalTo(CGSize(width: 35, height: 35))
        }
        
        // 昵称
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(iconImageView.snp_trailing).offset(10)
            make.top.equalTo(iconImageView)
        }
        
        //  会员等级
        mbrankImageView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(nameLabel.snp_trailing).offset(10)
            make.centerY.equalTo(nameLabel)
        }
        
        // 时间
        timeLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(nameLabel)
            make.bottom.equalTo(iconImageView)
        }
        
        // 来源
        sourceLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(timeLabel.snp_trailing).offset(10)
            make.bottom.equalTo(timeLabel)
        }
        
        // 认证
        verifiedImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(iconImageView.snp_trailing)
            make.centerY.equalTo(iconImageView.snp_bottom)
        }
        
        // 正文
        contentLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(iconImageView)
            make.top.equalTo(iconImageView.snp_bottom).offset(10)
            make.width.equalTo(kWidth-20)
        }
        
        // 配图约束
        pictureView.snp_makeConstraints { (make) -> Void in
            // make.size.equalTo(CGSize(width: 100, height: 100))
            make.top.equalTo(contentLabel.snp_bottom).offset(10)
            make.leading.equalTo(contentLabel)
        }
        
        // 自身的约束
        self.snp_makeConstraints { (make) -> Void in
            self.originalViewBottomConstraint = make.bottom.equalTo(pictureView).offset(10).constraint
        }
        
        
    }
    
    
    
    // MARK: - 懒加载控件
    
    // 头像
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))
    
    // 用户昵称
    private lazy var nameLabel: UILabel = {
       let nl = UILabel()
        nl.textColor = UIColor.darkGrayColor()
        nl.font = UIFont.systemFontOfSize(14)
        return nl
    }()
    
    // 会员等级
    private lazy var mbrankImageView: UIImageView = {
       let mv = UIImageView(image: UIImage(named: "common_icon_membership"))
        return mv
    }()
    
    // 时间
    private lazy var timeLabel: UILabel = {
       let tl = UILabel()
        tl.textColor = UIColor.orangeColor()
        tl.font = UIFont.systemFontOfSize(10)
        return tl
    }()
    
    // 来源
    private lazy var sourceLabel: UILabel = {
       let sl = UILabel()
        sl.textColor = UIColor.orangeColor()
        sl.font = UIFont.systemFontOfSize(10)
        return sl
    }()
    
    // 认证
    private lazy var verifiedImageView: UIImageView = UIImageView(image: UIImage(named: "avatar_vgirl"))
    
    // 微博正文
    private lazy var contentLabel: UILabel = {
       let cl = UILabel()
        cl.font = UIFont.systemFontOfSize(14)
        cl.textColor = UIColor.blackColor()
        cl.numberOfLines = 0
        return cl
    }()
    
    // 配图
    private lazy var pictureView: SYJPictureView = SYJPictureView()
    
    
    
}















